import time
from datetime import datetime, timezone
from tqsdk import TqApi, TqAuth, TqKq
from rich.console import Console
from rich.theme import Theme
from rich.table import Table
from rich.panel import Panel  # 保留导入（若后续需要面板）
from rich import box

# 控制台主题
custom_theme = Theme({
    "info": "bright_cyan",
    "warning": "bright_yellow",
    "error": "bright_red",
    "success": "bright_green",
    "trade": "bold bright_magenta"
})
console = Console(theme=custom_theme)


def ns_to_timestr(ns: int) -> str:
    """将纳秒时间戳转为本地时间字符串（若字段不存在或为0则返回'-'）"""
    try:
        if not ns:
            return "-"
        # TqSdk 通常以纳秒为单位
        sec = ns / 1_000_000_000
        dt = datetime.fromtimestamp(sec)
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception:
        return "-"


def is_today(ns: int) -> bool:
    """判断纳秒时间戳是否为今天（本地日期）"""
    try:
        if not ns:
            return False
        sec = ns / 1_000_000_000
        dt = datetime.fromtimestamp(sec)
        today = datetime.now().date()
        return dt.date() == today
    except Exception:
        return False


def main():
    try:
        console.print("正在登录天勤服务器并查询数据...", style="info")
        # 使用默认账号与密码（与现有脚本一致）
        api = TqApi(account=TqKq(), auth=TqAuth("cps168", "alibaba"))

        # 账户与持仓
        account = api.get_account()
        positions = api.get_position()

        
        if positions:
            table = Table(title="当前持仓", title_style="bold white on green", title_justify="center", show_header=True, header_style="bold black on #ADD8E6", box=box.SQUARE, border_style="cyan", show_lines=True, padding=(0,0))
            table.add_column("品种代码", style="bold", min_width=10)
            table.add_column("持仓(总)", justify="right", min_width=6)
            table.add_column("多仓", justify="right", min_width=6)
            table.add_column("空仓", justify="right", min_width=6)
            table.add_column("昨仓", justify="right", min_width=6)
            table.add_column("今仓", justify="right", min_width=6)
            for symbol, position in positions.items():
                pos_long = getattr(position, "pos_long", 0)
                pos_short = getattr(position, "pos_short", 0)
                pos_long_his = getattr(position, "pos_long_his", 0)
                pos_short_his = getattr(position, "pos_short_his", 0)
                pos_long_today = getattr(position, "pos_long_today", 0)
                pos_short_today = getattr(position, "pos_short_today", 0)
                total_pos = (pos_long or 0) + (pos_short or 0)
                total_his = (pos_long_his or 0) + (pos_short_his or 0)
                total_today = (pos_long_today or 0) + (pos_short_today or 0)
                table.add_row(f"{symbol}", f"{total_pos}", f"{pos_long}", f"{pos_short}", f"{total_his}", f"{total_today}")
            console.print(table)
        else:
            console.print("当前账户没有持仓。", style="warning")

        # 成交记录（当日）
        
        try:
            trades = api.get_trade()
        except Exception as e:
            trades = None
            console.print(f"获取成交记录失败: {e}", style="error")

        has_today_trade = False
        trade_table = Table(title="当日成交记录", title_style="bold white on green", title_justify="center", show_header=True, header_style="bold black on #ADD8E6", box=box.SQUARE, border_style="magenta", show_lines=True, padding=(0,0))
        trade_table.add_column("时间", justify="center", min_width=19)
        trade_table.add_column("合约", justify="center", min_width=12)
        trade_table.add_column("方向·开平", justify="center", min_width=8)
        trade_table.add_column("价格", justify="right", min_width=8)
        trade_table.add_column("数量", justify="right", min_width=6)
        trade_table.add_column("trade_id", style="dim")
        trade_table.add_column("order_id", style="dim")
        if trades:
            # 兼容字典或对象列表等结构
            items = trades.items() if hasattr(trades, 'items') else enumerate(trades)
            for _, trade in items:
                # 常见字段名：trade_date_time(纳秒), exchange_id, instrument_id, direction, offset, price, volume, trade_id, order_id
                t_ns = getattr(trade, "trade_date_time", None)
                if not is_today(t_ns):
                    continue
                has_today_trade = True
                time_str = ns_to_timestr(t_ns)
                ex = getattr(trade, "exchange_id", "-")
                ins = getattr(trade, "instrument_id", "-")
                direction = getattr(trade, "direction", "-")
                offset = getattr(trade, "offset", "-")
                price = getattr(trade, "price", "-")
                volume = getattr(trade, "volume", "-")
                trade_id = getattr(trade, "trade_id", "-")
                order_id = getattr(trade, "order_id", "-")
                trade_table.add_row(
                    f"{time_str}",
                    f"{ex}.{ins}",
                    f"{direction}/{offset}",
                    f"{price}",
                    f"{volume}",
                    f"{trade_id}",
                    f"{order_id}",
                )
            if has_today_trade:
                console.print(trade_table)

        if not has_today_trade:
            console.print("当日暂无成交记录。", style="warning")

        api.close()
        console.print("查询完成。", style="success")
    except Exception as e:
        console.print(f"运行出错: {e}", style="error")


if __name__ == "__main__":
    main()
